#include "picPublish.h"
#include "tpunb.h"
#include <time.h>
#include <libgen.h>
#include <devnode.h>
#include <mqtt_client.h>

#define FILE_PACK_SIZE	800

int hydrology_transform_send_file(char *filepath, char *filename)
{
	int fd;
	struct stat file_stat;
	int file_total_size;
	int ret;

	unsigned char buf[1024];
	hydrology_data_send_file_t *file_data;

	int maxline;
	char cmd[256] = {0};
	char file_md5sum[256] = {0};

	char file[256] = {0};

	int total_size_send = 0;

	sprintf(file, "%s/%s", filepath, filename);
	fd = open(file, O_RDONLY);
	if(fd < 0) {
		return -1;
	}

	fstat(fd, &file_stat);
	file_total_size = file_stat.st_size;
	if(file_total_size == 0) {
		close(fd);
		return -1;
	}

	maxline = 1;
	sprintf(cmd, "md5sum %s/%s", filepath, filename);
	myexec(cmd, file_md5sum, &maxline);	
	file_md5sum[32] = 0;
	DEBUG("file_total_size=%ld file_md5sum=%s", file_stat.st_size, file_md5sum);

	//构造数据
	file_data = (hydrology_data_send_file_t *)buf;
	file_data->total_size = file_total_size;
	strncpy(file_data->file_name, filename, sizeof(file_data->file_name));
	strncpy(file_data->file_md5sum, file_md5sum, sizeof(file_data->file_md5sum));

	file_data->offset_start = 0;
	file_data->offset_end = 0;
	
	while(1) {
		ret = read(fd, file_data->data, FILE_PACK_SIZE);
		if(ret <= 0) {
			break;
		}

		file_data->offset_end += ret;

		total_size_send += sizeof(hydrology_data_send_file_t) + ret + FRAME_PADDING_LEN;
		//DEBUG("range %d:%d len:%ld", file_data->offset_start, file_data->offset_end, sizeof(hydrology_data_send_file_t) + ret);
		hydrology_transform(HYD_CMD_PUSH_FILE, buf, sizeof(hydrology_data_send_file_t) + ret);
		file_data->offset_start += ret;
	}

	DEBUG("total_size_send=%d", total_size_send);

	close(fd);
	return 0;
}


static int get_filename_by_linkid(int id, char *filepath, char *filename)
{
	char *ptr;
	char link_file[256] = {0};
	char buf[256] = {0};
	sprintf(link_file, "%d", id);
	if(readlink(link_file, buf, sizeof(buf)) > 0) {
		ptr = strrchr(buf, '/');
		if(ptr) {
			ptr[0] = '\0';
			strcpy(filepath, buf);
		} else {
			strcpy(filepath, "./");
		}
		strcpy(filename, ptr+1);
		return 0;
	}
	
	return -1;
}

void picture_enqueue_by_linkid(int id)
{
	int ret;
	char filepath[256];
	char filename[256];

	ret = get_filename_by_linkid(id, filepath, filename);
	if(ret == 0) {
		DEBUG("filepath=%s filename=%s", filepath, filename);		
		hydrology_transform_send_file(filepath, filename);
	}
}
